<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: ProfileController.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_ProfileController extends Core_Controller_Action_Standard {
	public function init() {
		// @todo this may not work with some of the content stuff in here, double-check
		$subject = null;
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		if (! Engine_Api::_ ()->core ()->hasSubject ()) {
			$id = $this->_getParam ( 'id', $this->_getParam ( 'challenge_id', 0 ) );
			if (null !== $id) {
				$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
				$select = $table->select ();
				if (is_numeric ( $id )) {
					$select->where ( 'challenge_id = ?', $id );
				} else {
					$select->where ( 'slug = ?', $id );
				}
				$subject = $table->fetchRow ( $select );
				if ($subject && $subject->getIdentity () && (($subject->approved) || $subject->isOwner ( $viewer ))) {
					Engine_Api::_ ()->core ()->setSubject ( $subject );
				} else {
					return $this->_redirectCustom ( $this->view->url ( array (), 'vote_general' ), array ('reset' => true ) );
				}
			}
		}
		
		$url = $this->view->url ( array ('controller' => $subject->type, 'action' => 'browse' ), 'vote_general', true );
		$script = 'var tagAction = function(tag){window.location.href="' . $url . '/tag/"+tag}';
		$this->view->headScript ()->appendScript ( $script );
		
		$this->_helper->requireSubject ();
		$this->_helper->requireAuth ()->setNoForward ()->setAuthParams ( $subject, $viewer, 'view' );
	}
	
	public function indexAction() {
		$subject = Engine_Api::_ ()->core ()->getSubject ();
		$viewer = Engine_Api::_ ()->user ()->getViewer ();
		// Check block
		if ($viewer->isBlockedBy ( $subject )) {
			return $this->_forward ( 'requireauth', 'error', 'core' );
		}
		
		// Increment view count
		if (! $subject->getOwner ()->isSelf ( $viewer )) {
			$subject->view_count ++;
			$subject->save ();
		}
		
		// Get styles
		$table = Engine_Api::_ ()->getDbtable ( 'styles', 'core' );
		$select = $table->select ()->where ( 'type = ?', $subject->getType () )->where ( 'id = ?', $subject->getIdentity () )->limit ();
		
		$row = $table->fetchRow ( $select );
		
		if (null !== $row && ! empty ( $row->style )) {
			$this->view->headStyle ()->appendStyle ( $row->style );
		}
		
		// Render
		$this->_helper->content->setNoRender ()->setEnabled ();
	}
}